/* global $, visoConfig, Mustache, uuid, jsPlumb */
//查看流程图
(function () {
    //基本变量
    var flowNo = $("#diagramContainer-hidden").find("input[name='sysAuditRule.w_auditType']").val();//流程编号
    var taskNo = $("#diagramContainer-hidden").find("input[name='taskNo']").val();//当前任务正在执行任务编号
    var node_num = 0;//序号
    var areaId = "diagramContainer-main";//设计区域
    var jnode_areaId = '#'+areaId;//设计区域
    var enable_connect_server = true;//true/false 是否开启读后台服务请求数据
    //设置右侧【参数设置】组件可拖动
    // $("#diagramContainer-tools-box").draggable({containment: ".content-wrapper"}).resizable({containment: ".content-wrapper",minWidth: 150});
    // 设计区域屏蔽右键功能
    $(jnode_areaId).bind("contextmenu", function (e) {
        return false;
    });

    //定义节点样式
    var jnodeClassMap = {
        "start":"jnode-radius bdc-success",
        "task":"jnode-task bdc-primary",
        "judge":"jnode-diamond jnode-judge bdc-warning",
        "end":"jnode-radius bdc-danger"
    };
    if(strUtil.isNull(flowNo)){
        $(jnode_areaId).html("<div>流程编号为空，无法加载数据！</div>");
    }else{
        jsPlumb.ready(jsPlumbMain);//【第一次进入】 初始化jsPlumb执行其下定义的jsPlumbMain方法
    }

    //初始化节点设置
    function initSetNode (dataObj) {
        var id=dataObj.id;

        var isvisible = false;
        if("judge"==dataObj.jnodeType){
          isvisible = true;//只有【判断节点】显示线上的覆盖Label标签
        }
        //设置四周端点
        visioConfig.baseArchors.forEach(function (key) {
            console.log("addEndpoint on id",id);
          jsPlumb.addEndpoint(
              id,{
                  uuid: id+"-"+key,//给该端点加上一个uuid属性, 方便后续通过connect()方法，将两个断点链接上
                  anchors: key,
                  //连接器上的覆盖
                  connectorOverlays: [
                      ["Arrow", {width: 5, length: 5, location: 1, id: "arrow",visible: isvisible}],//连接器上配置的箭头
                      ["Label", {label: "表达式", id: "myLabel", cssClass: "connectorLabel",visible: isvisible}]
                  ]
              },visioConfig.hollowCircle2);
        });

        //让节点元素可拖动
        // jsPlumb.draggable(id, {containment: 'parent'});//containment: 'parent'只能在固定区域内移动
    }

    var tempHtml ='<div class="jnode-panel" id="{{id}}" style="top:{{x}}px;left:{{y}}px">';
        tempHtml +='<div class="jnode-box {{jnodeClass}}" jnode-type="{{jnodeType}}" jnode-num="{{jnodeNum}}" jnode-code="{{jnodeCode}}" jnode-last="{{jnodeLast}}" jnode-next="{{jnodeNext}}" jnode-rule="{{jnodeRule}}" rule-id="{{ruleId}}"><span>{{{jnodeName}}}</span></div>';
        tempHtml +='</div>';

    //利用mustache模板工具，把数据对象dataObj渲染为html
    function renderHtml (dataObj) {
        return Mustache.render(tempHtml, dataObj);
        //return Mustache.render(visioConfig.visioTemplate[templateId], dataObj);
    }

    //连接线时，初始化两端节点的相关属性。
    function addConnectSourceTarget(connInfo){
        var sourceObj = connInfo.source;
        var sourceUuid = sourceObj.id;
        var targetObj = connInfo.target;
        var targetUuid = targetObj.id;
        var targetJnodeName = targetObj.innerText;
        // console.log("connection sourceObj",sourceObj);
        // console.log("connection targetObj",targetObj);
        var lastCode = sourceObj.firstElementChild.getAttribute("jnode-code");
        var sourceJnodeType = sourceObj.firstElementChild.getAttribute("jnode-type");
        var nextCode = targetObj.firstElementChild.getAttribute("jnode-code");
        var targetJnodeType = targetObj.firstElementChild.getAttribute("jnode-type");
        var ruleVal = "";
        sourceObj.firstElementChild.setAttribute("jnode-next",nextCode);
        targetObj.firstElementChild.setAttribute("jnode-last",lastCode);
        var uuid_source_startpoint = connInfo.connection.endpoints[0].getUuid();
        var uuid_target_endpoint = connInfo.connection.endpoints[1].getUuid();
        var source_relKey=uuid_source_startpoint+"->"+uuid_target_endpoint;
        if(sourceJnodeType=="judge"){//判断条件节点。
            ruleVal = "result==T";
        }else{
            ruleVal = "";
            // nextCode = "";
        }
        if(targetJnodeType=="judge"){
            targetJnodeName = $(targetObj.firstElementChild.innerHTML).find("font").text();
        }
        var source_isRelKeyExist = false,target_isRelKeyExist = false;//据此判断是新增画线还是反显历史数据
        var source_ruleJson = {},target_ruleJson = {};
        var source_nexts=[],source_lasts=[],target_nexts=[],target_lasts=[];

        //给目标source节点的jnode-rule属性内，新增nexts目标关系
        var labelText = "";
        var source_jnodeRuleStr = sourceObj.firstElementChild.getAttribute("jnode-rule");
        if(!strUtil.isNull(source_jnodeRuleStr)){//非空时标识反显查找对应关系文本
            source_jnodeRuleStr = source_jnodeRuleStr.replace(/'/g,"\"");
            source_ruleJson = JSON.parse(source_jnodeRuleStr);
            source_nexts = source_ruleJson.nexts;
            source_lasts = source_ruleJson.lasts;
            for(var i=0; i<source_nexts.length; i++) {
                var item = source_nexts[i];
                var objsKey = item.source +"->"+ item.target;
                // if(item.id == targetUuid) {
                if(source_relKey == objsKey) {
                    // labelText = item.name+"-["+item.rule+"]";
                    labelText = item.name;
                    source_isRelKeyExist = true;//同关系已存在
                    // layer.msg("此关系已存在了，请删除！");
                    break;
                }
            }
        }
        if(!source_isRelKeyExist){ //没有就新增（新画的线），给sourceObj添加去往目标节点的关系rule
            labelText = "to "+targetJnodeName;
        }
        //修改连接线的覆盖文本
        connInfo.connection.getOverlay("myLabel").setLabel(labelText);
    }

    // jsPlumbMain 主要入口
    function jsPlumbMain () {
        jsPlumb.setContainer(areaId);
        // jsPlumb.bind('click', function (connection, originalEvent) {
        //     $(jnode_areaId).find(".jnode-panel").addClass("jnode-panel-active jnode-flicker");//当前节点选中，其他兄弟节点移除
        // });
        jsPlumb.bind("connection", function (connInfo, originalEvent) {
            // console.log("connection connInfo" ,connInfo);
            //console.log("connection originalEvent" ,originalEvent);
            if (connInfo.connection.sourceId == connInfo.connection.targetId) {
                jsPlumb.detach(connInfo);
                layer.msg("不能连接自己！");
            }else{
                addConnectSourceTarget(connInfo);
            }

        });

        initSearchAuditRuleJnodeData();//加载历史数据【第一次进入】
    }

    //初始化节点数据，进行修改
    function initSearchAuditRuleJnodeData() {
        var jnodeDataArray = [];//节点模拟数据
        var connectDataMap = {};//连接线模拟数据
        var req_url = common_list_url;
        if(!enable_connect_server){
            req_url = ctx+"/common/plateform/plugins/jvisio/test-data.js";
        }
        var index_load =  layer.load(1, {shade: false});//layer.msg("正在初始化");
        // var searchParamRules = {};
        // searchParamRules["pageName"] = "audit-rule-list";
        // searchParamRules["formName"] = "searchForm";
        // searchParamRules["sysAuditRule.w_auditType"] = "F002";
        // searchParamRules["orderBy"] = "sysAuditRule.num asc";
        $.getJSON(req_url,$("#searchForm_ruledata").serialize(),function(resultData){
            console.log("initSearchAuditRuleJnodeData",resultData);
            if(resultData.flag=="T"){
                //1、初始化节点
                jnodeDataArray = resultData.rows;
                node_num +=resultData.total;
                // console.log("rows-",JSON.stringify(resultData.rows));
                $.each(jnodeDataArray,function(index,item){
                    // console.log("item-"+index,item);
                    var dataObj = {};
                    var nodeType = item.nodeType;
                    var nodeConfigVal = item.nodeConfig;
                    if(!strUtil.isNull(nodeConfigVal)) {//新数据
                        dataObj = JSON.parse(nodeConfigVal);
                        var ruleJson ={};
                        ruleJson.nexts=dataObj.nexts;
                        ruleJson.lasts=dataObj.lasts;
                        dataObj.x=dataObj.x-4;
                        dataObj.y=dataObj.y-3;
                        var rulesJsonStr = JSON.stringify(ruleJson);//nexts.join("|");
                        dataObj.jnodeRule = rulesJsonStr.replace(/\"/g,"'");
                        // console.log("item-"+index,dataObj);
                    }else{
                        if(item.ifStart=="T"){
                            nodeType = "start";
                        }else if(item.next=="00"){
                            nodeType = "end";
                        }else{
                            nodeType = "task";
                        }
                        dataObj.id = uuid.v1();//.replace(/-/g,"");
                        dataObj.code = item.taskNo;
                        dataObj.x =  Math.floor(Math.random()*400);//随机数
                        dataObj.y = Math.floor(Math.random()*600);//随机数
                        dataObj.jnodeRule="";
                        dataObj.type = nodeType;
                        // dataObj.sourid = item;
                    }
                    var nodeNameText =strUtil.subStr2(((item.taskName.indexOf("]-")>-1)?item.taskName.split("]-")[1]:item.taskName),12);//dataObj.top+" x "+dataObj.left;
                    var taskNo = item.taskNo;
                    if(taskNo.length>2){
                        nodeNameText =nodeNameText;//+"-"+taskNo.substring(taskNo.length-2,taskNo.length);
                    }
                    dataObj.ruleId = item.ruleId;//记录业务数据主键id
                    dataObj.jnodeCode = item.taskNo;
                    dataObj.jnodeNum = item.num;
                    dataObj.jnodeName = nodeNameText;
                    dataObj.ifStart = item.ifStart;
                    dataObj.jnodeType = nodeType;//类型
                    dataObj.jnodeClass = jnodeClassMap[nodeType];
                    dataObj.jnodeLast=item.last;
                    dataObj.jnodeNext=item.next;
                    if("judge"==nodeType){
                        dataObj.jnodeName = "<i class='fa fa-plus-circle'></i><font class='hidden'>"+nodeNameText+"</font>";
                    }
                    // console.log("create init jnode dataObj",dataObj);
                    var targetHtml = renderHtml(dataObj);
                    $(jnode_areaId).append(targetHtml);//追加元素

                    initSetNode(dataObj);// 初始化节点设置

                    if(!strUtil.isNull(dataObj.nexts) && dataObj.nexts.length>0){//新数据
                        for (var i = 0; i <dataObj.nexts.length; i++){
                            var key = dataObj.nexts[i].source+"->"+dataObj.nexts[i].target;
                            connectDataMap[key]=dataObj.nexts[i];
                        }
                    }
                });
                //2、初始化连线
                // console.log("create init jnode connectDataMap",connectDataMap);
                if(Object.keys(connectDataMap).length>0){
                    for(var k in connectDataMap) {
                        var conObj = connectDataMap[k];
                        var uuid_source_endpoint =conObj.source;
                        var uuid_target_endpoint =conObj.target;
                        // console.log(connectDataMap);
                        jsPlumb.connect({uuids:[uuid_source_endpoint, uuid_target_endpoint]});
                    }
                }
            }
            layer.close(index_load);

            // var jnode_visited_array = ["start01","1543289988247","1543290666498"];//已结束节点
            // $.each(jnode_visited_array,function(index,item){
            //     $(jnode_areaId).find(".jnode-box[jnode-code="+item+"]").addClass("jnode-visited");
            // });
            // var jnode_active_array=["1543290673850"];//进行中的节点
            if(!strUtil.isNull(taskNo)){
            // $.each(jnode_active_array,function(index,item){
                var jnodeObj = $(jnode_areaId).find(".jnode-box[jnode-code="+taskNo+"]");
                // var jnode_type = jnodeObj.attr("jnode-type");
                // jnodeObj.addClass("jnode-active");
                jnodeObj.parent().addClass("jnode-panel-active");
            // });
            }

        });
    }



})()
